//
//  AppDelegate+HNSetupPush.m
//  ZYManagementSystem
//
//  Created by 星道 on 17/6/16.
//  Copyright © 2017年 焕宁. All rights reserved.
//

#import "AppDelegate+HNSetupPush.h"
#import "HNStrengtheningClassApplicationVC.h"
#import "HNSNGetMoneyVC.h"
#import "ZYNewsMessageController.h"
#import "XZStudentPayVC.h"

@implementation AppDelegate (HNSetupPush)
/**
 添加初始化APNs代码
 添加初始化JPush代码
 */
- (instancetype (^)(NSDictionary *))SetupPushNotifications
{
    return ^(NSDictionary *launchOptions) {




        //Required
        //notice: 3.0.0及以后版本注册可以这样写，也可以继续用之前的注册方式
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
            // 可以添加自定义categories
            // NSSet<UNNotificationCategory *> *categories for iOS10 or later
            // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
        }
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];


        [JPUSHService setupWithOption:launchOptions appKey:@"10ec6778dd2c6dde8697df58" channel:0 apsForProduction:NO];



        return self;
    };
}



/**
 设置极光推送的tag值
 */
+ (instancetype (^)(NSNumber *))SetupJPUSH_Tag
{
    return  ^(NSNumber *ID) {

        NSSet *Set = [NSSet setWithObject:[@"oid_" stringByAppendingString:[ID stringValue]]];
        [JPUSHService addTags:Set completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {

        } seq:0];
        return self;
    };
}


/**
 移除角标
 */
- (instancetype (^)())RemoveBadge
{
    return  ^() {

        // 唤醒APP时，清空角标
        [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
        [JPUSHService setBadge:0];
        return self;
    };
}

/**
 移除推送
 */
+ (instancetype (^)())DeleteJPUSH_Tag
{
    return  ^() {

        NSString *OID = [NSString stringWithFormat:@"oid_%@",[AccountTool shareAccountTool].currentAccount.uid];
        NSSet *Set = [NSSet setWithObjects:OID, nil];
        [JPUSHService deleteTags:Set completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {

        } seq:0];

        return self;
    };
}




/**
 注册APNs成功并上报DeviceToken

 请在AppDelegate.m实现该回调方法并添加回调方法中的代码
 */
- (instancetype (^)(NSData *))RegisterDeviceToken
{
    return ^(NSData *deviceToken) {

        /// Required - 注册 DeviceToken
        [JPUSHService registerDeviceToken:deviceToken];

        return self;
    };
}





#pragma mark - iOS10以上的消息处理
/**
 添加处理APNs通知回调方法
 这个方法是前端收到通知就走，不管有没有点击
 */
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        
    }
    completionHandler(UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionBadge); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}




/** 不管是前端还是后端，收到消息并点击之后就会执行这个方法 */
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        // 移除角标
        self.RemoveBadge ();
        // 延迟一秒
        [self performSelector:@selector(goToVC:) withObject:userInfo afterDelay:1.f];
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}


#pragma mark - iOS7.0-10.0消息处理
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
//    NSLog(@"尼玛的推送消息呢===%@",userInfo); // 取得 APNs 标准信息内容，如果没需要可以不取
//    NSDictionary *aps = [userInfo valueForKey:@"aps"];
//    NSString *content = [aps valueForKey:@"alert"]; //推送显示的内容
//    NSInteger badge = [[aps valueForKey:@"badge"] integerValue];
//    NSString *sound = [aps valueForKey:@"sound"]; //播放的声音 // 取得自定义字段内容，userInfo就是后台返回的JSON数据，是一个字典
//    [JPUSHService handleRemoteNotification:userInfo];
//    application.applicationIconBadgeNumber = 0;
}









// 跳转界面
- (void)goToVC:(NSDictionary *)dict {
    
    NSInteger index = [[dict valueForKey:@"extra1"] integerValue];
    
    // 如果没有登录的话一律打开应用后不处理
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"loginState"] == NO) {
        
        return;
    }
    
    
    // 1 金牌加强课-用户申请
    if (index == 1) {
        
        HNStrengtheningClassApplicationVC *vc = [[HNStrengtheningClassApplicationVC alloc] init];
        [self navigationControllerWithVC:vc];
    }
    
    // 2 资金管理-课程提现
    if (index == 2) {
        HNSNGetMoneyVC *VC = [[HNSNGetMoneyVC alloc] init];
        VC.title = @"课程提现";
        VC.HNSNGetMoneyType = HNSNGetMoneyTypeNormalZiJin;
        [self navigationControllerWithVC:VC];
    }
    
    // 2 机构或老师-新消息
    if (index == 3) {
        ZYNewsMessageController *vc = [ZYNewsMessageController new];
        [self navigationControllerWithVC:vc];
    }
    
    // 4 缴费学生
    if (index == 4) {
        
        XZStudentPayVC *vc = [[XZStudentPayVC alloc] init];
        vc.isFlang = @"YES";
        vc.dateArr = @[[NSString getCurrentDateYearMD], [NSString currentDateTow]];
        [self navigationControllerWithVC:vc];
    }
}

/** 建立导航并跳转 */
- (void)navigationControllerWithVC:(UIViewController *)VC {
    
    UIViewController *rootVC = [self topMostController];
    XDNavigationController *nav = [[XDNavigationController alloc] initWithRootViewController:VC];
    VC.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTargat:self action:@selector(dissmis) image:@"nav_icon_back_default" highImage:@"nav_icon_back_default"];
    [rootVC presentViewController:nav animated:YES completion:nil];
}

/** 返回 */
- (void)dissmis {
    
    [[self topMostController] dismissViewControllerAnimated:YES completion:nil];
}

/** 获取最上层的控制器 */
- (UIViewController *) topMostController {
    UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;
    
    while (topController.presentedViewController) {
        topController = topController.presentedViewController;
    }
    
    return topController;
}

@end
